<template>
  <el-dialog class="entrust-agreement-book-dialog" width="1200px" :visible.sync="dialogVisible" title="技术服务委托协议书"
    :close-on-click-modal="false" v-dialogDrag="true" @open="handleDialogOpen" @closed="handleDialogClosed">
    <div class="document-container">
      <div class="contract-info">
        <div><strong>单位编号：</strong>{{ formData.unitNumber }}</div>
        <div><strong>合同编号：</strong>{{ formData.agreementNumber }}</div>
      </div>

      <h2 class="document-title">技术服务委托协议书</h2>

      <div class="section-title">合同双方</div>
      <table>
        <tr>
          <th width="15%">甲方（委托方）</th>
          <td>{{ formData.organizationName }}</td>
        </tr>
        <tr>
          <th>乙方（受委托方）</th>
          <td>{{ formData.deptName }}</td>
        </tr>
      </table>

      <div class="section-title">合同条款</div>
      <div class="clause"><strong>第一条：</strong>本合同经双方平等协商，在真实、充分的表达各自意愿的基础上，依据《中华人民共和国民法典》的规定，达成本协议，并由双方共同恪守。</div>

      <div class="clause"><strong>第二条：</strong>甲方委托乙方进行技术服务的相关内容：</div>
      <table>
        <tr>
          <th width="120px">委托项目</th>
          <th>具体内容</th>
          <th width="120px">单价(元)</th>
          <th width="120px">数量</th>
          <th width="120px">金额(元)</th>
          <!-- <th width="80px"></th> -->
        </tr>
        <tr v-for="(item, index) in formData.serviceContents || []">
          <td>
            <el-checkbox v-model="item.checkboxInspecId" label="3">防护检测</el-checkbox>
            <br />
            <el-radio-group v-model="item.radioInspecId">
              <el-radio style="margin-right: 0px;" label="5">验收检测</el-radio><br />
              <el-radio style="margin-right: 0px;" label="2">状态检测</el-radio><br />
              <el-radio style="margin-right: 0px;" label="4">稳定性检测</el-radio>
            </el-radio-group>
            <br />
            <el-checkbox v-model="item.checkboxInspecId2" label="9">环境检测</el-checkbox>
          </td>
          <td>
            <el-input style="width: 100%;" v-model="item.specificContent" placeholder=""></el-input>
          </td>
          <td class="text-right">
            <el-input-number style="width: 100%;" v-model="item.salesUnitPrice" placeholder="" :controls="false"
              :precision="2" :min="0" @change="calcAmount(item)"></el-input-number>
          </td>
          <td class="text-center">
            <el-input-number style="width: 100%;" v-model="item.quantity" placeholder="" :controls="false"
              :precision="0" :min="0" @change="calcAmount(item)"></el-input-number>
          </td>
          <td class="text-right">
            <el-input-number style="width: 100%;" v-model="item.amount" placeholder="" :controls="false" :precision="2"
              :min="0" @change="calcPrice(item)"></el-input-number>
          </td>
          <!-- <td>
            <div style="display: flex; justify-content: center; align-items: center; height: 90px;">
              <span style="
                  display: inline-block;
                  width: 50px;
                  padding: 2px 0;
                  border: 1px solid #ccc;
                  color: #888;
                  border-radius: 2px;
                  cursor: pointer;
                  position: relative;
                  z-index: 999;
                  text-align: center;
                " @click="handleDelServiceContent(index)">-</span>
            </div>
          </td> -->
        </tr>
        <!-- <tr>
          <td colspan="6" style="text-align: center;">
            <span style="
                display: inline-block;
                width: 50px;
                padding: 2px 0;
                border: 1px solid #ccc;
                color: #888;
                border-radius: 2px;
                cursor: pointer;
                position: relative;
                z-index: 999;
                text-align: center;
              " @click="handleAddServiceContent">+</span>
          </td>
        </tr> -->
        <tr>
          <td colspan="4" class="text-right"><strong>合计</strong></td>
          <td class="text-right"><strong>{{ formData.signAmount }}</strong></td>
        </tr>
      </table>

      <div class="clause"><strong>第三条：</strong>甲方责任:按时提供服务所需资料，并对真实性、准确性负责，配合乙方按时进行技术服务，按照合同约定及时支付服务费用给乙方。</div>

      <div class="clause"><strong>第四条：</strong>乙方责任:乙方自所需资料提供齐全之日起30个工作日内，提供成果文件。</div>

      <div class="clause"><strong>第五条：</strong>双方保密义务：对于甲乙双方提供的数据及资料，双方负有保密义务。未经对方许可，不得泄露和转让给第三方。</div>

      <div class="clause"><strong>第六条：</strong>甲方向乙方支付技术服务报酬及支付方式等：</div>
      <div class="clause">1、技术服务费总额为大写：<u>{{ formData.signAmountCapital }}</u>，小写￥：<u>{{ formData.signAmount }}</u>元。
      </div>
      <div class="clause">2、技术服务费支付时间：乙方收到甲方相应款项后7个工作日内及时交付成果文件。</div>
      <div class="clause">3、因甲方资料提供不准确导致报告错误或者偏差，需重新出具报告并进行技术服务所需费用，由甲方承担。</div>

      <div class="clause"><strong>第七条：</strong>违约责任</div>
      <div class="clause">1、合同生效后如任意一方单方面解除合同，应由要求解除合同方按合同额的5%赔付对方违约金。</div>
      <div class="clause">2、合同未尽事宜，双方应本着互惠互利的原则协商解决，若协商不成，向乙方所在地人民法院提起诉讼解决。</div>

      <div class="clause"><strong>第八条：</strong>其他约定事项：无</div>

      <div class="clause"><strong>第九条：</strong>本协议书一式两份，双方签字或盖章后生效，扫描复印件均有效，甲乙双方各执一份。</div>

      <div class="clause"><strong>第十条：</strong>本合同有效期至本合同全部条款履行完毕后截止。</div>

      <div class="signature-section">
        <div class="signature-box">
          <h4>甲方（盖章）{{ formData.organizationName }}</h4>
          <div class="signature-item">
            <div class="signature-label">统一社会信用代码：</div>
            <div class="signature-value"></div>
          </div>
          <div class="signature-item">
            <div class="signature-label">地址：</div>
            <div class="signature-value">{{ }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">联系人：</div>
            <div class="signature-value"></div>
          </div>
          <div class="signature-item">
            <div class="signature-label">电话：</div>
            <div class="signature-value"></div>
          </div>
          <div class="signature-item">
            <div class="signature-label">开户银行：</div>
            <div class="signature-value"></div>
          </div>
          <div class="signature-item">
            <div class="signature-label">账号：</div>
            <div class="signature-value"></div>
          </div>
          <div class="signature-item" style="margin-top: 20px;">
            <div class="signature-label">法定代表人/委托代理人：</div>
            <div class="signature-value" style="border-bottom: 1px solid #999; min-height: 30px;"></div>
          </div>
          <div class="signature-item" style="margin-top: 10px;">
            <div class="signature-label">日期：</div>
            <div class="signature-value">{{ parseTime(new Date(), '{y}年{m}月{d}日') }}</div>
          </div>
        </div>

        <div class="signature-box">
          <h4>乙方（盖章）{{ formData.deptName }}</h4>
          <div class="signature-item">
            <div class="signature-label">统一社会信用代码：</div>
            <div class="signature-value">{{ formData.licenseNumber }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">地址：</div>
            <div class="signature-value">{{ formData.address }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">联系人：</div>
            <div class="signature-value">{{ formData.contactsName }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">电话：</div>
            <div class="signature-value">{{ formData.contactsMobile }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">开户银行：</div>
            <div class="signature-value">{{ formData.openBank }}</div>
          </div>
          <div class="signature-item">
            <div class="signature-label">账号：</div>
            <div class="signature-value">{{ formData.account }}</div>
          </div>
          <div class="signature-item" style="margin-top: 20px;">
            <div class="signature-label">法定代表人/委托代理人：</div>
            <div class="signature-value" style="border-bottom: 1px solid #999; min-height: 30px;">
              <div class="sign-box" @click="showSignDialog = true">
                <img :src="formData.partyBSignUrl" alt="">
                <span v-if="!formData.partyBSignUrl">点击此处签名</span>
              </div>
            </div>
          </div>
          <div class="signature-item" style="margin-top: 10px;">
            <div class="signature-label">日期：</div>
            <div class="signature-value">{{ parseTime(new Date(), '{y}年{m}月{d}日') }}</div>
          </div>
        </div>
      </div>

      <div class="section-title">附表：放射工作人员信息表</div>
      <table class="complex-table">
        <tr>
          <th colspan="5">单位名称：（盖章）{{ formData.organizationName }}</th>
        </tr>
        <tr>
          <th width="15%">职业照种类代码：</th>
          <td colspan="4"></td>
        </tr>
        <tr>
          <th>照射源</th>
          <th colspan="4">职业分类及其代号</th>
        </tr>
        <tr>
          <td rowspan="3">1 核燃料循环</td>
          <td>铀矿开采1A</td>
          <td>铀矿加工1B</td>
          <td></td>
          <td>铀富集和转化1C</td>
        </tr>
        <tr>
          <td>核燃料制造1D</td>
          <td>反应堆运行1E</td>
          <td></td>
          <td>核燃料后处理1F</td>
        </tr>
        <tr>
          <td>核燃料循环系统的研究开发1G</td>
          <td>退役及废物管理1H</td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td rowspan="2">2 医学应用</td>
          <td>诊断放射学2A</td>
          <td>牙科放射学2B</td>
          <td></td>
          <td>核医学2C</td>
        </tr>
        <tr>
          <td>放射治疗2D</td>
          <td>介入放射学2E</td>
          <td></td>
          <td>其他应用2F</td>
        </tr>
        <tr>
          <td rowspan="3">3 工业应用</td>
          <td>工业辐照3A</td>
          <td>工业探伤3B</td>
          <td></td>
          <td>发光涂料3C</td>
        </tr>
        <tr>
          <td>放射性同位素生产3D</td>
          <td>测井3E</td>
          <td></td>
          <td>加速器运行3F</td>
        </tr>
        <tr>
          <td>其他应用3G</td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td rowspan="2">4 天然源</td>
          <td>民用航空4A</td>
          <td>煤矿开采4B</td>
          <td></td>
          <td>其他矿藏开采4C</td>
        </tr>
        <tr>
          <td>石油和天然气工业4D</td>
          <td>矿物和矿石处理4E</td>
          <td></td>
          <td>其他4F</td>
        </tr>
        <tr>
          <td>5 国防活动</td>
          <td>核潜艇及支持设备5A</td>
          <td>其他防卫活动5B</td>
          <td></td>
          <td></td>
        </tr>
        <tr>
          <td>6 其他</td>
          <td>教育6A</td>
          <td>兽医学6B</td>
          <td></td>
          <td>其他6C</td>
        </tr>
      </table>

      <div class="note">
        <p><strong>填表须知：</strong></p>
        <p>1、职业照射种类代码按上表中的内容选项。</p>
        <p>2、从事放射工作时间：按从事时的年月日填写，如有中断时间须填写年限。</p>
        <p>3、剂量计编号按发放剂量计标签上编号填写。</p>
      </div>

      <div class="section-title">附表：个人剂量监测人员</div>
      <table>
        <tr>
          <th width="150px">编号</th>
          <th width="150px">姓名</th>
          <th width="150px">性别</th>
          <th width="150px">职业类别</th>
          <th width="80px"></th>
        </tr>
        <tr v-for="(item, index) in formData.monitorStaffs || []">
          <td>
            <el-input style="width: 100%;" v-model="item.staffNumber" placeholder=""></el-input>
          </td>
          <td>
            <el-input style="width: 100%;" v-model="item.staffName" placeholder=""></el-input>
          </td>
          <td>
            <el-select style="width: 100%;" v-model="item.sex" clearable placeholder="请选择">
              <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </td>
          <td>
            <el-select style="width: 100%;" v-model="item.occupationCategory" clearable placeholder="请选择">
              <el-option v-for="dict in dict.type.occupational_classification" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </td>
          <td style="text-align: center;">
            <span style="
                display: inline-block;
                width: 50px;
                padding: 2px 0;
                border: 1px solid #ccc;
                color: #888;
                border-radius: 2px;
                cursor: pointer;
                position: relative;
                z-index: 999;
                text-align: center;
              " @click="handleDelMonitorStaff(index)">-</span>
          </td>
        </tr>
        <tr>
          <td colspan="5" style="text-align: center;">
            <span style="
                display: inline-block;
                width: 50px;
                padding: 2px 0;
                border: 1px solid #ccc;
                color: #888;
                border-radius: 2px;
                cursor: pointer;
                position: relative;
                z-index: 999;
                text-align: center;
              " @click="handleAddMonitorStaff">+</span>
          </td>
        </tr>
      </table>
    </div>

    <div class="dialog-footer" slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button style="margin-right: 50px;" type="primary" @click="handleSave">保存</el-button>
      <el-button style="margin-right: 50px;" type="primary" @click="handleGen"
        v-if="formData.agreementEntrustId">生成</el-button>
      <el-button style="margin-right: 50px;" type="primary" @click="handleView"
        v-if="formData.entrustOssId">查看</el-button>
      <el-button style="margin-right: 50px;" type="primary" @click="handleDownload"
        v-if="formData.entrustOssId">下载</el-button>
    </div>

    <Sign :show.sync="showSignDialog" @sign-success="(data) => {
      formData.partyBSign = data.ossId
      formData.partyBSignUrl = data.url
    }"></Sign>

    <el-dialog width="500px" :visible.sync="dialogVisible2" title="生成技术服务委托协议书" append-to-body
      :close-on-click-modal="false" v-dialogDrag="true" @open="handleDialogOpen2" @closed="handleDialogClosed2">
      <span>生成类型：</span>
      <el-radio v-model="formData2.isPdf" :label="true">pdf</el-radio>
      <el-radio v-model="formData2.isPdf" :label="false">docx</el-radio>

      <span>需要盖章：</span>
      <el-radio v-model="formData2.isStamp" :label="true">是</el-radio>
      <el-radio v-model="formData2.isStamp" :label="false">否</el-radio>

      <div class="dialog-footer" slot="footer">
        <el-button @click="dialogVisible2 = false">取消</el-button>
        <el-button style="margin-right: 50px;" type="primary" @click="handleGenerate">确定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  entrustAgreementBookDetail,
  entrustAgreementBookAdd,
  entrustAgreementBookEdit,
  entrustAgreementBookGenerator
} from '@/api/entrustReceipt/index2.js'
import Sign from '@/components/Sign'
import { listByIds } from '@/api/system/oss'
import { signToPdf } from "@/api/basicData/template";

export default {
  name: 'EntrustAgreementBook',
  components: {
    Sign
  },
  dicts: ['occupational_classification', 'sys_user_sex'],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    agreementId: {
      type: String,
      default: '',
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      operType: 'add',
      formData: {},
      showSignDialog: false,

      formData2: {},
      dialogVisible2: false,
    }
  },
  created() {
    this.initFormData()
    this.initFormData2()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      this.getEntrustAgreementBookDetail()
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.operType = 'add'
      this.initFormData()
      this.initFormData2()
    },
    // 弹框打开时
    handleDialogOpen2() {
    },
    // 弹框关闭时
    handleDialogClosed2() {
      this.initFormData2()
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        serviceContents: [],
        monitorStaffs: [],
      }
    },
    // 初始化表单数据2
    initFormData2() {
      this.formData2 = {
        agreementId: '',
        isPdf: true,
        isStamp: true,
      }
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.agreementId = this.agreementId
      data.serviceContents?.forEach(item => {
        if (item.checkboxInspecId && item.radioInspecId) {
          item.entrustedProject = '3,' + item.radioInspecId
        } else if (item.checkboxInspecId) {
          item.entrustedProject = '3'
        } else if (item.radioInspecId) {
          item.entrustedProject = item.radioInspecId
        }
        if (item.checkboxInspecId2) {
          item.entrustedProject += ',9'
        }
      })
      return data
    },
    // 获取表单数据
    getFormData2() {
      const data = JSON.parse(JSON.stringify(this.formData2))
      data.agreementId = this.agreementId
      return data
    },
    // 获取技术服务委托协议书详情
    getEntrustAgreementBookDetail() {
      entrustAgreementBookDetail(this.agreementId).then(res => {
        res.data?.serviceContents?.forEach((item) => {
          if (item.entrustedProject?.includes('3')) {
            item.checkboxInspecId = true
          }
          if (item.entrustedProject?.includes('9')) {
            item.checkboxInspecId2 = true
          }
          item.radioInspecId = item.entrustedProject?.replace(/,3|3,|3|,9|9,|9/g, '')
        })

        this.formData = res.data || {}
        if (this.formData.partyBSign) {
          listByIds(this.formData.partyBSign).then(res => {
            this.formData.partyBSignUrl = res.data[0].url
            this.$forceUpdate()
          }).catch(err => { })
        }
        if (this.formData.agreementEntrustId) {
          this.operType = 'edit'
        } else {
          this.operType = 'add'
        }
      }).catch(err => { })
    },
    // 点击保存
    handleSave() {
      const data = this.getFormData()
      let fn = null
      if (this.operType == 'add') fn = entrustAgreementBookAdd
      else if (this.operType == 'edit') fn = entrustAgreementBookEdit

      fn(data).then(res => {
        this.$message.success('操作成功')
        entrustAgreementBookDetail(this.agreementId).then(res => {
          this.formData.agreementEntrustId = res.data.agreementEntrustId
          if (this.formData.agreementEntrustId) {
            this.operType = 'edit'
          } else {
            this.operType = 'add'
          }
          this.$forceUpdate()
        }).catch(err => { })
      }).catch(err => { })
    },
    // 点击生成
    handleGen() {
      this.dialogVisible2 = true
    },
    // 确认生成
    handleGenerate() {
      const data = this.getFormData2()
      entrustAgreementBookGenerator(data).then(res => {
        this.$message.success('操作成功')
        this.dialogVisible2 = false
        entrustAgreementBookDetail(this.agreementId).then(res => {
          this.formData.agreementEntrustId = res.data.agreementEntrustId
          if (this.formData.agreementEntrustId) {
            this.operType = 'edit'
          } else {
            this.operType = 'add'
          }
          this.formData.entrustOssId = res.data.entrustOssId
          this.$forceUpdate()
        }).catch(err => { })
      }).catch(err => { })
    },
    // 点击查看
    handleView() {
      if (!this.formData.entrustOssId) {
        uni.showToast({ title: '请先生成技术服务委托协议书' })
        return
      }
      signToPdf(this.formData.entrustOssId).then((response) => {
        let blob = new Blob([response], {
          type: "application/pdf;chartset=UTF-8",
        });
        let fileURL = URL.createObjectURL(blob);
        window.open(fileURL);
      }).catch(err => { })
    },
    handleDownload() {
      listByIds(this.formData.entrustOssId).then(res => {
        if (!res.data[0]) return
        const file = res.data[0]
        fetch(file.url).then(response => response.blob()).then(blob => {
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = `${this.formData.agreementNumber}${this.formData.organizationName}`
          document.body.appendChild(link)
          link.click()
          window.URL.revokeObjectURL(url)
          link.remove()
        })
      }).catch(err => {})
    },
    // 添加服务内容行
    handleAddServiceContent() {
      if (!this.formData.serviceContents) {
        this.formData.serviceContents = []
      }
      this.formData.serviceContents?.push({})
    },
    // 删除服务内容行
    handleDelServiceContent(index) {
      this.formData.serviceContents?.splice(index, 1)
    },
    // 计算单价
    calcPrice(row) {
      if (!row.quantity || !row.amount) {
        row.salesUnitPrice = ''
        return
      }
      row.salesUnitPrice = (row.amount / row.quantity).toFixed(2)
    },
    // 计算金额
    calcAmount(row) {
      if (!row.quantity || !row.salesUnitPrice) {
        row.amount = ''
        return
      }
      row.amount = (row.quantity * row.salesUnitPrice).toFixed(2)
    },
    // 计算合计金额
    calcTotalAmount() {
      let totalAmount = 0
      this.formData.serviceContents?.forEach((item) => {
        if (item.amount) {
          totalAmount += parseFloat(item.amount)
        }
      })
      this.formData.signAmount = totalAmount.toFixed(2)
      this.formData.signAmountCapital = this.amountToChinese(Number(this.formData.signAmount))
    },
    // 添加个人剂量监测人员行
    handleAddMonitorStaff() {
      if (!this.formData.monitorStaffs) {
        this.formData.monitorStaffs = []
      }
      this.formData.monitorStaffs?.push({})
    },
    // 删除个人剂量监测人员行
    handleDelMonitorStaff(index) {
      this.formData.monitorStaffs?.splice(index, 1)
    },

    // 金额大写转换
    amountToChinese(amount) {
      // 处理无效输入
      if (typeof amount !== 'number' || isNaN(amount)) {
        return
      }

      // 金额为0的情况
      if (amount === 0) {
        return '零元整';
      }

      // 处理负数
      let sign = '';
      if (amount < 0) {
        sign = '负';
        amount = Math.abs(amount);
      }

      // 数字映射
      const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
      const units = ['', '拾', '佰', '仟'];
      const bigUnits = ['', '万', '亿'];

      // 将金额转为字符串并分割为整数和小数部分
      const [integerPart, decimalPart = ''] = amount.toFixed(2).split('.');

      // 转换整数部分 - 使用分组方法
      let intStr = integerPart;
      // 反转整数部分字符串
      intStr = intStr.split('').reverse().join('');
      // 分割成4位一组
      const sectionGroups = [];
      for (let i = 0; i < intStr.length; i += 4) {
        sectionGroups.push(intStr.substring(i, i + 4));
      }
      // 反转sectionGroups，得到从高位节到低位节
      sectionGroups.reverse();

      let chineseInteger = '';
      for (let k = 0; k < sectionGroups.length; k++) {
        // 当前节字符串（反转过的，低位在前）
        let sec = sectionGroups[k];
        // 反转该节，得到正常顺序（高位在前）
        sec = sec.split('').reverse().join('');
        // 转换当前节
        let sectionStr = '';
        let hasZero = false; // 节内是否有未添加的零

        for (let j = 0; j < sec.length; j++) {
          const digit = sec[j];
          const d = parseInt(digit);
          // 节内位置：j（0表示最高位）
          // 单位下标 = sec.length - 1 - j
          const unitIndex = sec.length - 1 - j;
          const unit = unitIndex < units.length ? units[unitIndex] : '';

          if (d === 0) {
            hasZero = true;
          } else {
            if (hasZero) {
              sectionStr += '零';
              hasZero = false;
            }
            sectionStr += digits[d] + unit;
          }
        }

        // 节单位处理
        const bigUnitIndex = sectionGroups.length - 1 - k;
        let bigUnit = '';
        if (bigUnitIndex < bigUnits.length) {
          bigUnit = bigUnits[bigUnitIndex];
        } else {
          // 处理万亿以上单位
          const cycle = bigUnitIndex % 2;
          bigUnit = cycle === 1 ? '万' : '亿';
        }

        // 如果节字符串不为空，添加节单位
        if (sectionStr !== '') {
          chineseInteger += sectionStr + bigUnit;
        }
      }

      // 如果整数部分为空，设为"零"
      if (chineseInteger === '') {
        chineseInteger = '零';
      }

      // 转换小数部分
      let chineseDecimal = '';
      if (decimalPart) {
        const jiao = parseInt(decimalPart[0]); // 角
        const fen = parseInt(decimalPart[1]);  // 分

        if (jiao > 0) {
          chineseDecimal += digits[jiao] + '角';
        }
        if (fen > 0) {
          chineseDecimal += digits[fen] + '分';
        }
      }

      // 组合结果
      let result = sign;
      result += chineseInteger;
      result += '元';
      result += chineseDecimal || '整';

      // 清理多余的"零元"
      return result.replace(/零元$/, '元');
    }
  },
  watch: {
    'formData.serviceContents': {
      deep: true,
      handler(val) {
        this.calcTotalAmount()
      },
      immediate: true
    }
  }
}
</script>

<style lang="scss" scoped>
.entrust-agreement-book-dialog {

  ::v-deep .el-dialog__body {
    height: 80vh;
    overflow-y: auto;

    .document-container {
      max-width: 1000px;
      margin: 0 auto;
      background-color: white;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
      padding: 40px;
      position: relative;
    }

    .document-title {
      text-align: center;
      font-size: 24px;
      font-weight: bold;
      margin: 20px 0;
      color: #1a3c6c;
      text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
    }

    .contract-info {
      display: flex;
      justify-content: space-between;
      margin: 15px 0;
      padding: 0 10px;
    }

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin: 20px 0 10px;
      padding-left: 10px;
      border-left: 4px solid #1a3c6c;
      color: #1a3c6c;
    }

    table {
      width: 100%;
      border-collapse: collapse;
      margin: 10px 0 20px;
      table-layout: fixed;
    }

    th,
    td {
      border: 1px solid #999;
      padding: 8px 10px;
      text-align: left;
      vertical-align: top;
    }

    th {
      background-color: #e9f0f8;
      font-weight: bold;
      text-align: center;
    }

    .text-center {
      text-align: center;
    }

    .text-right {
      text-align: right;
    }

    .signature-section {
      display: flex;
      justify-content: space-between;
      margin: 40px 0;
    }

    .signature-box {
      width: 48%;
      padding: 15px;
      border: 1px solid #ccc;
      background-color: #f9f9f9;
    }

    .signature-box h4 {
      text-align: center;
      margin-bottom: 15px;
      color: #1a3c6c;
    }

    .signature-item {
      margin: 8px 0;
      display: flex;
    }

    .signature-label {
      width: 100px;
      font-weight: bold;
    }

    .signature-value {
      flex: 1;
    }

    .sign-box {
      display: inline-flex;
      align-items: center;
      padding: 0 10px;
      width: 200px;
      height: 50px;
      border-radius: 4px;
      border: 1px solid #DCDFE6;
      cursor: pointer;
      vertical-align: middle;
      position: relative;
      z-index: 99;

      img {
        height: 100%;
      }

      span {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    .footer-note {
      margin-top: 30px;
      padding-top: 15px;
      border-top: 1px solid #ccc;
      font-size: 12px;
      color: #666;
      text-align: center;
    }

    .clause {
      margin: 15px 0;
      line-height: 1.8;
      text-indent: 2em;
    }

    .note {
      font-size: 12px;
      color: #666;
      margin-top: 5px;
    }

    .complex-table th,
    .complex-table td {
      text-align: center;
      vertical-align: middle;
    }

    .sub-table {
      margin: 0;
      width: 100%;
    }

    .sub-table td {
      border: none;
      padding: 5px;
    }

    .highlight {
      background-color: #fffde7;
    }

    .no-border td {
      border: none;
    }
  }
}
</style>
